package com.vitas.coin.vm

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.snap.base.util.BaseUtil
import com.snap.common.main.BaseVM
import com.vitas.coin.R
import com.vitas.coin.data.bean.LocalMusicInfoBean
import com.vitas.coin.data.event.ChooseEvent
import com.vitas.coin.manager.LocalMusicManager

class LocalMusicVM : BaseVM() {

    private var mLocalMusicManager: LocalMusicManager? = null

    private var mMusicList: List<LocalMusicInfoBean>? = null

    lateinit var actionAct: () -> FragmentActivity



    private fun initLocalData() {
        mMusicList = ArrayList<LocalMusicInfoBean>()
        if (mLocalMusicManager == null) {
            mLocalMusicManager = LocalMusicManager.getInstance(actionAct.invoke())
        }
        mMusicList = mLocalMusicManager?.allMusic
    }

    fun loadData() {
        initLocalData()
    }


    val musicAdapter by lazy { LocalMusicAdapter() }


    inner class LocalMusicAdapter : RecyclerView.Adapter<LocalMusicAdapter.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_local_music, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            mMusicList?.get(position).apply {
                holder.tv_name.text = mMusicList?.get(position)?.songName
                holder.tv_choose.setOnClickListener { v ->
                    mMusicList?.get(position)?.let {
                        BaseUtil.postEvent(ChooseEvent(it))
                        actionAct.invoke().finish()
                    }
                }
            }
        }

        override fun getItemCount(): Int {
            return mMusicList!!.size
        }

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val tv_name: TextView = itemView.findViewById(R.id.tv_name)
            val tv_choose: TextView = itemView.findViewById(R.id.tv_choose)
        }

    }


}